package com.online.websocketcluster.util;

import com.online.websocketcluster.entity.HbEntity;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 心跳机制存储工具类
 *
 * @author hsc
 * @create 2018-04-26 18:10
 */
public  class HbUtils implements Runnable {
    public static  final Map<Integer, HbEntity> HBMAPS = new ConcurrentHashMap<Integer, HbEntity>();

    @Override
    public void run() {
        while (true){
            //迭代map，判断每一个value值里面的hbTime是否超时。
            Set<Map.Entry<Integer, HbEntity>> set = HBMAPS.entrySet();
            Iterator<Map.Entry<Integer, HbEntity>> hbIterator = set.iterator();
            while(hbIterator.hasNext()){
                Map.Entry<Integer, HbEntity> item = hbIterator.next();
                HbEntity hbEntity = item.getValue();
                // 心跳时间
                Long hbTime = hbEntity.getHbTime();
                // 当前系统时间
                Long now = System.currentTimeMillis();
                // 心跳超时 close session。
                if (now - hbTime >= 70000){
                    Session session = hbEntity.getSession();
                    try {
                        session.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                //不超时，不处理。

                //线程休眠3000ms
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }


    }

}
